package com.cj.bus.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public final class FileUtil {


	public static File saveFile(MultipartFile file, String filePath) {
		//校验后缀
   	 String fileName = file.getOriginalFilename();
   	 String serverPath = filePath + "/" + DateUtil.formatYmd(LocalDateTime.now());
   	 File localFile = new File(serverPath);
     if(!localFile .exists()) {
            localFile.mkdirs();
       }
       int index = fileName.lastIndexOf(".");
       File serverFile = null;
       try {
    	// 文件扩展名
   		String fileSuffix = fileName.substring(index);
   		String newFileName = fileMd5(file.getInputStream());
          //日期
        String targetFilePath = serverPath+"/" +newFileName+fileSuffix;
       	serverFile = new File(targetFilePath);
		file.transferTo(serverFile);
		} catch (Exception e) {
			log.error("文件上传异常",e);
			return null;
		}

		return serverFile;
	}
	
	
	public static String fileMd5(InputStream inputStream) {
		try {
			return DigestUtils.md5Hex(inputStream);
		} catch (IOException e) {
			log.error("FileUtil->fileMd5:{}" ,e.getMessage());
		}
		return null;
	}
	
	public static String fileMd5(File file) {
		try {
			return DigestUtils.md5Hex(new FileInputStream(file));
		} catch (IOException e) {
			log.error("FileUtil->fileMd5:{}" ,e.getMessage());
		}
		return null;
	}
	
}
